package com.hj.system.base.utils;

import com.hj.system.base.domain.Tree;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

public class BuildTree {


    /**
     * jstree 树
     */
    public static <T> Tree<T> build4Depth(List<Tree<T>> nodes, String idParam, String name) {
        List<Tree<T>> trees = buildList4Depth(nodes, idParam);
        Tree<T> root;
        if (trees != null && trees.size() == 1) {
            root = trees.get(0);
        } else {
            root = new Tree<>();
            root.setId(idParam);
            root.setParentId("-1");
            root.setHasParent(false);
            root.setHasChildren(true);
            root.setChecked(true);
            root.setChildren(trees);
            root.setText(name);
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            root.setState(state);
            root.setChildren(trees);
        }
        return root;
    }

    public static <T> List<Tree<T>> buildList4Depth(List<Tree<T>> nodes, String idParam) {
        if (nodes == null) {
            return null;
        }
        Queue<Tree> queue = new LinkedBlockingQueue<>();
        List<Tree<T>> root = new ArrayList<>();
        nodes.stream().filter(s -> idParam.equalsIgnoreCase(s.getParentId())).forEach(t -> {
            queue.add(t);
            t.setHasParent(true);
            root.add(t);
        });
        while (!queue.isEmpty()) {
            Tree<T> parent = queue.poll();
            nodes.stream().filter(t -> parent.getId().equalsIgnoreCase(t.getParentId())).forEach(t -> {
                t.setHasParent(true);
                parent.setHasChildren(true);
                parent.getChildren().add(t);
                queue.add(t);
            });
        }
        return root;
    }

}